<template>
	<el-dialog :title="titleMap[mode]" v-model="visible" :width="1300" destroy-on-close @closed="$emit('closed')"
			   align-center :close-on-click-modal="false" :close-on-press-escape="mode != 'show' ? false : true">
		<el-form :model="form" :rules="rules" :disabled="mode == 'show'" ref="dialogForm" label-width="100" label-position="right" style="height:650px;overflow:auto;overflow-x:hidden;">
			<el-row :gutter="1">
				<el-col :span="6">
					<el-form-item label="关联销售" prop="contract_id">
						<el-input v-model="contract_code" placeholder="请选择销售" @click="checkContract" readonly></el-input>
					</el-form-item>
				</el-col>
				<el-col :span="6">
					<el-form-item label="生产单号" prop="production_code">
						<el-input v-model="form.production_code" placeholder="生产单号(不填写自动生成)" clearable></el-input>
					</el-form-item>
				</el-col>
				<el-col :span="6">
					<el-form-item label="开单日期" prop="open_date">
						<el-date-picker v-model="form.open_date" type="date" placeholder="请选择日期" :value-format="'YYYY-MM-DD'" style="width:100%"/>
					</el-form-item>
				</el-col>
				<el-col :span="6">
					<el-form-item label="交货日期" prop="over_date">
						<el-date-picker v-model="form.over_date" type="date" placeholder="请选择日期" :value-format="'YYYY-MM-DD'" style="width:100%"/>
					</el-form-item>
				</el-col>
			</el-row>
			<el-col :span="6">
				<el-form-item label="优先级" prop="level">
					<el-select v-model="form.level" placeholder="请选择" style="width:100%" clearable>
						<el-option label="正常" :value="1"/>
						<el-option label="加急" :value="2"/>
						<el-option label="延期" :value="3"/>
					</el-select>
				</el-form-item>
			</el-col>
			<el-row :gutter="1">
				<el-col :span="12">
					<el-form-item label="备注" prop="remark">
						<el-input v-model="form.remark" placeholder="备注" type="textarea" clearable></el-input>
					</el-form-item>
				</el-col>
				<el-col :span="12">
					<el-form-item label="附件" prop="enclosure">
						<sc-upload-file v-model="form.enclosure" :is_same_name="1">
							<el-button type="primary" icon="el-icon-upload">选择文件</el-button>
						</sc-upload-file>
					</el-form-item>
				</el-col>
			</el-row>
			<el-col :span="24">
				<el-form-item label="商品清单" prop="detail">
                    <div class="flex">
                        <el-button type="primary" size="small" icon="el-icon-plus" @click="checkGoods">选择商品</el-button>
                        <el-form-item label="扫码录入">
                            <div style="display:flex;width:100%">
                                <el-input v-model="bar_code" ref="barInput" v-if="barInput == 0" @input="handInput"></el-input>
                                <el-switch v-model="barInput" :active-value="0" :inactive-value="1" @change="barChange"></el-switch>
                            </div>
                        </el-form-item>
                    </div>
					<sc-form-table ref="table" v-model="form.detail" :addTemplate="addTemplate" placeholder="暂无数据" height="400" hideAdd>
						<el-table-column prop="goods_code" label="商品编码" align="center">
							<template #default="scope">
								{{ scope.row.goods_code }}
							</template>
						</el-table-column>
						<el-table-column label="商品图片" align="center">
							<template #default="scope">
								<el-image v-if="scope.row.goods_image" style="width: 30px; height: 30px; border-radius: 5px;" :src="scope.row.goods_image" :preview-src-list="[scope.row.goods_image]" preview-teleported="true" hide-on-click-modal align="center"></el-image>
							</template>
						</el-table-column>
						<el-table-column prop="goods_name" label="商品名称" align="center">
							<template #default="scope">
								{{ scope.row.goods_name }}
							</template>
						</el-table-column>
						<el-table-column prop="goods_spec" label="规格型号" align="center">
							<template #default="scope">
								{{ scope.row.goods_spec }}
							</template>
						</el-table-column>
						<el-table-column prop="unit_name" label="单位" align="center">
							<template #default="scope">
								{{ scope.row.unit_name }}
							</template>
						</el-table-column>
						<el-table-column label="生产数量" prop="number" align="center">
							<template #default="scope">
								<el-input v-model="scope.row.number" placeholder="生产数量" @input="totalCompute" @focus="onFocus($event)"></el-input>
							</template>
						</el-table-column>
					</sc-form-table>
				</el-form-item>
			</el-col>
		</el-form>
		<template #footer>
			<el-button @click="visible = false">取 消</el-button>
			<el-button v-if="mode != 'show'" type="primary" :loading="isSaveing" @click="submit(0)">保 存</el-button>
			<el-button v-if="mode == 'add' || mode == 'copy'" type="primary" :loading="isSaveing" @click="submit(1)">保存并审核</el-button>
		</template>
	</el-dialog>
	<select-goods v-if="dialog.goods" ref="goodsDialog" @success="goodsUpdate" @closed="dialog.goods=false" :query="{system_disable:0}"></select-goods><!-- 商品 -->
	<select-contract v-if="dialog.contract" ref="contractDialog" @success="contractUpdate" @closed="dialog.contract=false" :query="{status:1}"></select-contract><!-- 销售 -->
</template>

<script>
import SelectContract from '../../sale/contract/selectContract.vue';
import selectGoods from '../../goods/info/selectGoods.vue';

export default {
	components: {selectGoods, SelectContract},
	emits: ['success', 'closed'],
	data() {
		return {
			mode: "add",
			titleMap: {
				add: '新增生产单',
				mrpadd: '新增生产单',
				edit: '编辑生产单',
				production: '添加生产单',
				show: '查看'
			},
			visible: false,
			isSaveing: false,
			//表单数据
			form: {
				id: "",
				production_code: "",
				contract_id: "",
				open_date: this.moment().format('YYYY-MM-DD'),
				over_date: "",
				level: 1,
				enclosure: "",
				remark: "",
				detail: [],
			},
			//验证规则
			// rules: {
			// 	contract_id: [{ required: true, message: '请选择销售' }],
			// },
			contract_code: "",
			addTemplate: {},
			dialog: {
				goods: false,
				contract: false,
			},
			disabled: false,
            barInput: 1,
            bar_code: "",
		}
	},
    created() {
        this.handInput = this.debounce(this.handInput, 500);
	},
	mounted() {
	},
	methods: {
        // 防抖
        debounce(func, delay){
            let timeoutId;
            return function(...args) {
                if (timeoutId) {
                    clearTimeout(timeoutId);
                }
                timeoutId = setTimeout(() => {
                    func.apply(this, args);
                }, delay);
            };
        },
        handInput(e){
            this.getProduct(e)
        },
        async getProduct(e){
            if(!e){
                return
            }
            var res = await this.$API.goods.goods.search.get({ bar_code:e });
            let exist = this.common.isExist(res.data.id, this.form.detail, 'goods_id')
            if (exist) {
                this.form.detail.map(item1=>{
                    if(item1.goods_id == res.data.id){
                        item1.number += 1
                    }
                })
            }else{
                if(res.data.id){
                    let array = []
                    array.push({
                        goods_id: res.data.id,
                        goods_name: res.data.goods_name,
                        goods_spec: res.data.goods_spec,
                        unit_name: res.data.unit && res.data.unit.unit_name,
                        goods_code: res.data.goods_code,
                        number:1
                    })
                    this.form.detail = [...this.form.detail, ...array]
                }
            }
            this.bar_code = ""
        },
		//显示
		open(mode = 'add') {
			this.mode = mode;
			this.visible = true;
			return this
		},
		//表单提交方法
		submit(e) {
			this.form.is_check = e
			this.$refs.dialogForm.validate(async (valid) => {
				if (valid) {
					this.isSaveing = true;
					var res = [];
					if (this.form.id) {
						res = await this.$API.production.plan.edit.post(this.form);
					} else {
						res = await this.$API.production.plan.add.post(this.form);
					}
					this.isSaveing = false;
					if (res.code == 1) {
						this.$emit('success', this.form, this.mode)
						this.visible = false;
						this.$message.success("操作成功")
					} else {
						this.$alert(res.message, "提示", {type: 'error'})
					}
				} else {
					return false;
				}
			})
		},
		//表单注入数据
		async setData(data) {
			this.form.id = data.id
			var res = await this.$API.production.plan.detail.get({id: data.id});
			this.form.production_code = data.production_code
			this.form.contract_id = data.contract_id
			this.contract_code = data.contract && data.contract.contract_code
			this.form.open_date = data.open_date
			this.form.over_date = data.over_date
			this.form.level = data.level
			this.form.enclosure = data.enclosure
			this.form.remark = data.remark
			let array = []
			res.data.detail.map(item => {
				array.push({
					id: item.id,
					goods_id: item.goods_id,
					goods_code: item.goods && item.goods.goods_code,
					goods_name: item.goods && item.goods.goods_name,
					goods_image: item.goods && item.goods.goods_image,
					goods_spec: item.goods && item.goods.goods_spec,
					unit_name: item.goods && item.goods.unit && item.goods.unit.unit_name,
					number: item.number,
				})
			})
			this.form.detail = array
		},
		createProduct(data) {
			console.log('data :>> ', data);
			this.form.contract_id = data.contract_id
			this.contract_code = data.contract_code
			let array = []
			data.data.map(item => {
				array.push({
					goods_id: item.goods_id,
					goods_name: item.goods_name,
					unit_name: item.unit_name,
					goods_code: item.goods_code,
					goods_spec: item.goods_spec,
					number: item.number,
				})
			})
			this.form.detail = array
		},
		onFocus(event) {
			event.target.select();
		},
		checkContract() {
			if (!this.disabled) {
				this.dialog.contract = true
				this.$nextTick(() => {
					this.$refs.contractDialog.open('add')
				})
			}
		},
		contractUpdate(data) {
			this.form.contract_id = data.id
			this.contract_code = data.contract_code
			let array = []
			data.product.map(item => {
				array.push({
					goods_id: item.goods_id,
					goods_name: item.goods && item.goods.goods_name,
					goods_image: item.goods && item.goods.goods_image,
					goods_spec: item.goods && item.goods.goods_spec,
					unit_name: item.goods && item.goods.unit && item.goods.unit.unit_name,
					goods_code: item.goods && item.goods.goods_code,
					number:item.sale_num?item.sale_num:1
				})
				this.form.detail = array
			})
		},
		// 选择商品
		checkGoods(e) {
			this.dialog.goods = true
			this.$nextTick(() => {
				this.$refs.goodsDialog.open('add').setData(e)
			})
		},
		goodsUpdate(data) {
			let array = []
			data.map((item) => {
				array.push({
					goods_id: item.id,
					goods_name: item.goods_name,
					goods_image: item.goods_image,
					goods_spec: item.goods_spec,
					unit_name: item.unit_name,
					goods_code: item.goods_code,
					number:1
				})
			})
			let existingIds = this.form.detail.map(item => item.goods_id);
			for (let i = array.length - 1; i >= 0; i--) {
				if (existingIds.includes(array[i].goods_id)) {
					array.splice(i, 1);
				}
			}
			this.form.detail = [...this.form.detail, ...array]
		},
        barChange(e){
            if(e == 0){
                this.$nextTick(()=>{
                    this.$refs.barInput.focus()
                })
            }
        },
	}
}
</script>

<style>
.flex{
    width: 100%;
    display: flex;
    justify-content: space-between;
    padding-right: 35px;
}
</style>
